...接續
fn main() {
let sum = 1 + 2;
let difference = 5.5 - 4.2;
let product = 2 * 15;
let quotient = 16.7 / 2.4;
let floored = 2 / 3; // 0
let remainder = 13 % 2;
}
陳述式與表達式
而函式本體是由一系列的陳述式(statements)並在最後可以選擇加上表達式(expression)來組成
fn main() {
println!("Hello, world!");
test_func();
arg_func(5);
let res = return_value_func(2);
println!("result is {}",res);
}
fn test_func() {
println!("Test function!");
}
fn arg_func(x: i32) {
println!("x : {}", x);
}
fn return_value_func(x: i32) -> i32 {
x+2
}
if 表達式
fn main() {
test_func(1);
test_func(2);
test_func(3);
// 在let(Statements)中用if
let condition = true;
let number = if condition { 5 } else { 6 }; // 將Statements的result 賦值(assign)給變數
println!("num is:{}", number);
}
fn test_func(num: i32) -> () {
if num % 3 == 0 {
println!("{}被3整除", num);
} else if num % 3 == 1 {
println!("{}被3除餘1", num);
} else if num % 3 == 2 {
println!("{}被3除餘2", num);
} else {
println!("Err");
}
}
迴圈類型:loop
、while
和for
loop
會讓Rust反覆不停地執行一段code直到你親自告訴它要停下來
fn main() {
loop {
println!("run");
}
}
使用while做迴圈
fn main() {
let mut number = 5;
while number != 0 {
println!("num: {}", number);
number -= 1;
}
}
使用while
遍歷集合(a
)
fn main() {
let a = [1, 2, 3, 4, 5];
let mut i = 0;
while i < 5 {
println!("num:{}", a[i]);
i += 1;
}
}
使用for迴圈遍歷集合
fn main() {
let a = [1, 2, 3, 4, 5];
for element in a {
println!("num:{}", element);
}
}
今天就簡單的紀錄到這邊,明天繼續研究並整理rust的一些重要功能